package com.mark.conf;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @Description: Swagger2的配置类
 * @Author: Mark
 * @CreateDate: 2018/9/21 9:39
 * @Version: 2.0
 * @Copyright : 豆浆油条个人非正式工作室
 */
@Configuration
@EnableSwagger2
public class MySwagger2Conf {
    /**
     * 多个包路径的分割符
     */
    private static final String SPLITOR = ";";

    @Bean
    public Docket createResApi(){
        //扫描控制的包路径
        final String basePackagePath = "com.mark.web.data.controller";
        //shiro权限控制的相关的控制器包的路径
        final String sysBashPackagePath = "com.mark.web.sys.controller";
        //账单模块的控制器包路径
        final String billBashPackagePath = "com.mark.web.bill.controller";
        //星运里的错的控制器
        final String starsBashPackagePath = "com.mark.web.stars.controller";

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(this.getApiInfo())
                .select()
                .apis(basePackage(basePackagePath+SPLITOR+sysBashPackagePath+SPLITOR+billBashPackagePath+SPLITOR+starsBashPackagePath))
                .paths(PathSelectors.any())
                .build();
    }

    private Predicate<RequestHandler> basePackage(String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage)     {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackage.split(SPLITOR)) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }

    /**
     * 配置文档在线显示时的基本信息
     * @return ApiInfo对象
     */
    private ApiInfo getApiInfo() {
        return new ApiInfoBuilder()
                .title("CampusO2O在线接口文档")
                .description("在线文档详细版-->https://www.showdoc.cc/campuso2o")
                .termsOfServiceUrl("https://www.showdoc.cc/campuso2o")
                .contact(new Contact("Mark","https://blog.csdn.net/ycd500756","1685368363@qq.com"))
                .version("2.0")
                .build();
    }
}
